﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Jinndev.Async {

    public class AsyncTaskQueue : TaskQueue {

        private List<Func<Task>> funcList = new List<Func<Task>>();
        private int index;

        public AsyncTaskQueue(string description) : base(description) {

        }

        public AsyncTaskQueue(string description, params Func<Task>[] funcs) : base(description) {
            funcList.AddRange(funcs);
        }

        public void Add(Func<Task> func) {
            funcList.Add(func);
        }

        public override bool HasNext() {
            return index < funcList.Count;
        }

        public async override Task InvokeNextAsync() {
            if (HasNext()) {
                Func<Task> func = funcList[index++];
                await func?.Invoke();
            }
        }

        public override void InvokeNext() {
            if (HasNext()) {
                Func<Task> func = funcList[index++];
                func?.Invoke();
            }
        }

        public override float GetProgress() {
            if (funcList.Count > 0) {
                return (float)index / funcList.Count;
            }
            return 1;
        }

        public override int GetCount() {
            return funcList.Count;
        }

    }

}
